#include "AnimalFactory.h"
#include <iostream>
#include <stdexcept>

AnimalFactory::AnimalFactory(const std::string &libraryPath)
    : handle(nullptr), libraryPath(libraryPath) {
  // 加载动态链接库
  handle = dlopen(libraryPath.c_str(), RTLD_LAZY);
  if (!handle) {
    throw std::runtime_error("Failed to open library: " +
                             std::string(dlerror()));
  }
}

AnimalFactory::~AnimalFactory() {
  if (handle) {
    dlclose(handle);
  }
}

AnimalApiPtr AnimalFactory::createAnimal(const std::string &name) const {
  // 清除之前的错误
  dlerror();

  // 加载符号
  using CreateAnimalFunc = AnimalApiPtr (*)(const std::string &);
  CreateAnimalFunc createFunc =
      reinterpret_cast<CreateAnimalFunc>(dlsym(handle, "create_animal"));

  const char *dlsym_error = dlerror();
  if (dlsym_error) {
    throw std::runtime_error("Failed to load symbol 'create_animal': " +
                             std::string(dlsym_error));
  }

  // 创建动物对象
  return createFunc(name);
}